package nju.software.tagmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import nju.software.tagmanager.mapper.CategoryMapper;
import nju.software.tagmanager.mapper.RelCategoryTagMapper;
import nju.software.tagmanager.mapper.TagMapper;
import nju.software.tagmanager.pojo.dto.CategoryPageQueryDTO;
import nju.software.tagmanager.pojo.dto.ServiceQueryDTO;
import nju.software.tagmanager.pojo.entity.Category;
import nju.software.tagmanager.pojo.entity.RelCategoryTag;
import nju.software.tagmanager.pojo.vo.CategoryVO;
import nju.software.tagmanager.pojo.vo.TagVO;
import nju.software.tagmanager.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 97942
 * @description 针对表【category(标签类别)】的数据库操作Service实现
 * @createDate 2024-01-12 16:03:24
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private TagMapper tagMapper;

    @Resource
    private RelCategoryTagMapper relCategoryTagMapper;


    @Override
    public List<Category> find(ServiceQueryDTO query) {
        return categoryMapper.find(query);
    }

    @Override
    public IPage<CategoryVO> search(CategoryPageQueryDTO query) {
        Page<CategoryVO> page = new Page<>(query.getPage(), query.getLimit());
        IPage<CategoryVO> result = categoryMapper.search(query, page);
        result.getRecords().forEach(record -> {
            record.setTags(tagMapper.findByCategoryId(record.getId()));
        });
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCascadeById(Integer categoryId) {
        List<Integer> tagIds = tagMapper.findOnlyFollowing(categoryId).stream()
                .map(TagVO::getId)
                .collect(Collectors.toList());
        relCategoryTagMapper.delete(new QueryWrapper<RelCategoryTag>()
                .eq("category_id", categoryId));
        if (!tagIds.isEmpty()) {
            tagMapper.deleteBatchIds(tagIds);
        }
        categoryMapper.deleteById(categoryId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Integer categoryId) {
        relCategoryTagMapper.delete(new QueryWrapper<RelCategoryTag>()
                .eq("category_id", categoryId));
        categoryMapper.deleteById(categoryId);
    }
}




